package quq.missq.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import quq.missq.BaseActivity;
import quq.missq.Constants;
import quq.missq.MLog;
import quq.missq.R;
import quq.missq.adapter.BigShootDetailAdapter;
import quq.missq.beans.BigShootDetailBean;
import quq.missq.beans.CommentsBean;
import quq.missq.beans.UserBean;
import quq.missq.utils.UserTools;
import quq.missq.utils.VolleyTool;
import quq.missq.views.LoadMoreListView;
import quq.missq.views.ShareDialog;

/**
 * Created by River on 8/3/15.
 */
public class BigShootDetailActivity extends BaseActivity implements VolleyTool.HTTPListener,
        LoadMoreListView.OnLoadMore,View.OnClickListener{

    private LoadMoreListView mListView;
    private LinkedList<CommentsBean.Result> results;
    private BigShootDetailAdapter adapter;
    private BigShootDetailBean mDetail = null;

    private ImageView mBack;
    private ImageView mShare;
    private ImageView mComment;
    private ImageView mBLike;
    private ImageView mBUnlike;
    private ImageView mLike;
    private ImageView mUnlike;

    private int targetType = 1; //  1:大招/话题
    private int id = -1;
    private boolean desc = true;// 排序，true:时间倒序, false:时间正序
    private int maxResults = 10;
    private int currentPage = 1;
    private TextView tvFavors;

    UserBean.User user = null;
    private NetworkImageView avtar;
    private ImageView mTypeIcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.big_shoot_detail_activity);
        id = getIntent().getExtras().getInt("id");
        user = UserTools.getUser(this);
        MLog.e("打开了大招");
        initView();
        initListener();
        initBigShootData();
    }

    private void initView(){
        mListView = (LoadMoreListView)findViewById(R.id.listView);
        mBack = (ImageView)findViewById(R.id.back);
        mShare = (ImageView)findViewById(R.id.share);
        mComment = (ImageView)findViewById(R.id.comment);
        mBLike = (ImageView)findViewById(R.id.like);
        mBUnlike = (ImageView)findViewById(R.id.unlike);
    }

    private void initCommentData(){
        results = new LinkedList<>();
        adapter = new BigShootDetailAdapter(this,1,id);
        View view = getHeadView();
        mListView.addHeaderView(view);
        adapter.setData(results);
        mListView.setAdapter(adapter);
        loadCommentNetworkData();
    }

    private View getHeadView(){
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.big_shoot_detail_head_layout,null);
        ((TextView)view.findViewById(R.id.title)).setText(mDetail.getData().getTitle());
        mTypeIcon = (ImageView) view.findViewById(R.id.typeIcon);
        if(mDetail.getData().getCategory().getId() == 3){
            mTypeIcon.setImageResource(R.mipmap.icon_plan);
        }else if(mDetail.getData().getCategory().getId() == 2){
            mTypeIcon.setImageResource(R.mipmap.icon_change);
        }else if(mDetail.getData().getCategory().getId() == 1){
            mTypeIcon.setImageResource(R.mipmap.icon_night);
        }else if(mDetail.getData().getCategory().getId() == 5){
            mTypeIcon.setImageResource(R.mipmap.icon_qa);
        }else if (mDetail.getData().getCategory().getId() == 4){
            mTypeIcon.setImageResource(R.mipmap.icon_show);
        }
        (view.findViewById(R.id.jubao)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(user != null){
                    showDialog();
                }else{
                    goLogin();
                }
            }
        });
        ((TextView)view.findViewById(R.id.level)).setText("level " + mDetail.getData().getAuthor().getLevel());
        String gender = "男";
        if(mDetail.getData().getAuthor().getGender() == 1){
            gender = "男";
        }else{
            gender = "女";
        }
        mLike = (ImageView)view.findViewById(R.id.like);
        mUnlike = (ImageView)view.findViewById(R.id.unlikeIcon);
        int liked = mDetail.getData().getFavored();
        if(liked == 0){
            changeLike(0);
        }else{
            changeLike(1);
        }
        tvFavors = (TextView)view.findViewById(R.id.favors);
        tvFavors.setText(mDetail.getData().getFavors() + "");
        mLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                likeOrUnlike(1);
                int count = Integer.parseInt(tvFavors.getText().toString());
                tvFavors.setText((count - 1) + "");
            }
        });
        mUnlike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                likeOrUnlike(0);
                int count = Integer.parseInt(tvFavors.getText().toString());
                tvFavors.setText((count + 1) + "");
            }
        });
        ((TextView)view.findViewById(R.id.gender)).setText(gender);
        ((NetworkImageView)view.findViewById(R.id.avtar)).setImageUrl(Constants.IMAGE_HOST + mDetail.getData().getAuthor().getAvatar(), VolleyTool.getImageLoader());
        (view.findViewById(R.id.avtar)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BigShootDetailActivity.this,TaPageActivity.class);
               // intent.setClass(BigShootDetailActivity.this, TaPageActivity.class);
                intent.putExtra("uid", mDetail.getData().getAuthor().getId());
                intent.putExtra("username", mDetail.getData().getAuthor().getNkname());
                startActivity(intent);
            }
        });
        ((TextView)view.findViewById(R.id.name)).setText(mDetail.getData().getAuthor().getNkname());
        ((TextView)view.findViewById(R.id.time)).setText(mDetail.getData().getCreated());
        ((TextView)view.findViewById(R.id.likeCount)).setText(mDetail.getData().getComments() + "");
        WebView content = (WebView) view.findViewById(R.id.content);

        //Log.e("BigShootDetailActivity",mDetail.getData().getContent());

        content.setWebViewClient(new MyWebViewClient());
        MLog.e(mDetail.getData().getContent());
        content.getSettings().setJavaScriptEnabled(true);
//        content.getSettings()
        content.loadDataWithBaseURL(null, mDetail.getData().getContent(), "text/html", "UTF-8", null);
        //content.loadDataWithBaseURL(null, "http://www.baidu.com", "text/html", "UTF-8", null);
        view.findViewById(R.id.avtarLayout).setOnClickListener(this);

        return view;
    }
    /**
     * 测试这里做webView内嵌连接的处理
     */
    class MyWebViewClient extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    private void changeLike(int k){
        if(k == 0){
            mLike.setVisibility(View.GONE);
            mUnlike.setVisibility(View.VISIBLE);
            mBLike.setVisibility(View.GONE);
            mBUnlike.setVisibility(View.VISIBLE);
        }else{
            mLike.setVisibility(View.VISIBLE);
            mUnlike.setVisibility(View.GONE);
            mBLike.setVisibility(View.VISIBLE);
            mBUnlike.setVisibility(View.GONE);
        }
    }

    private void likeOrUnlike(int viewId){
        if(user == null) {
            Intent intent1 = new Intent();
            intent1.setClass(this, LoginActivity.class);
            startActivity(intent1);
        }else{
            Map<String,String> params = new HashMap<>();
            params.put("id",id+"");
            params.put("acc_token",user.getAcc_token());
            String url = "";
            if(viewId == 0){
                changeLike(1);
                url = Constants.FAVOR_BIG_SHOOT_URL;
            }else{
                changeLike(0);
                url = Constants.UNFAVOR_BIG_SHOOT_URL;
            }
            VolleyTool.get(this,url,params,this,1,null);
        }
    }

    private void initBigShootData(){
        Map<String,String> params = new HashMap<>();
        params.put("id",id+"");
        if(user != null){
            params.put("acc_token",user.getAcc_token());
        }
        VolleyTool.get(this,Constants.GET_BIG_SHOOT_DETAIL_URL,params,this,Constants.GET_BIG_SHOOT_DETAIL, BigShootDetailBean.class);
    }

    private void loadCommentNetworkData(){
        Map<String,String> params = new HashMap<>();
        params.put("targetId",id+"");
        params.put("pn",currentPage+"");
        params.put("maxResults",maxResults+"");
        params.put("desc",desc+"");
        VolleyTool.get(this,Constants.GET_COMMENTS_LIST_URL, params, this, Constants.GET_COMMENTS_LIST, CommentsBean.class);
    }

    private void initListener(){
        mBack.setOnClickListener(this);
        mShare.setOnClickListener(this);
        mComment.setOnClickListener(this);
        mListView.setLoadMoreListen(this);
        mBLike.setOnClickListener(this);
        mBUnlike.setOnClickListener(this);
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        if(requestCode == Constants.GET_COMMENTS_LIST){
            CommentsBean bean = (CommentsBean)t;
            if(bean.getCode() >= 0){
                LinkedList<CommentsBean.Result> beans = bean.getData().getResults();
                if(currentPage == 1){
                    adapter.getData().clear();
                    adapter.getData().addAll(0, beans);
                    adapter.notifyDataSetChanged();
                }else{
                    if(beans.size() > 0){
                        adapter.getData().addAll(beans);
                        adapter.notifyDataSetChanged();
                    }else{
                        if(results.size() > 10){
                            showToast("已加载完所有");
                        }
                    }
                    mListView.onLoadComplete();
                }
            }else{
                showToast(bean.getMessage());
            }
        }else if(requestCode == Constants.GET_BIG_SHOOT_DETAIL){
            mDetail = (BigShootDetailBean)t;
            initCommentData();
        }

    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {

    }

    @Override
    public void loadMore() {
        currentPage = currentPage+1;
        loadCommentNetworkData();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.comment:
                if(user != null){
                intent = new Intent();
                intent.putExtra("targetType",1);
                intent.putExtra("targetId",id);
                intent.setClass(this,PublishComentActivity.class);
                goOtherAcitity(intent);
                }else{
                    goLogin();
                }
                break;
            case R.id.like:
                if(user != null){
                if(tvFavors != null){
                changeLike(0);
                likeOrUnlike(1);
                int count = Integer.parseInt(tvFavors.getText().toString());
                tvFavors.setText((count-1)+"");}
                }else{
                    goLogin();
                }
                break;
            case R.id.unlike:
                if(user != null) {
                    if (tvFavors != null) {
                        changeLike(1);
                        likeOrUnlike(0);
                        int count1 = Integer.parseInt(tvFavors.getText().toString());
                        tvFavors.setText((count1 + 1) + "");
                    }
                }else{
                    goLogin();
                }
                break;
            case R.id.share:
                if(user!=null) {
                    ShareDialog shareDialog = new ShareDialog(BigShootDetailActivity.this);
                    shareDialog.setData_1(mDetail.getData());
                    shareDialog.setType(1);
                    shareDialog.show();
                }else{
                    goLogin();
                }
                break;
            case R.id.yingxiao:
                jubaoType = 1;
                sendReport();
                break;
            case R.id.yingsui:
                jubaoType = 2;
                sendReport();
                break;
            case R.id.bushi:
                jubaoType = 3;
                sendReport();
                break;
            case R.id.mingan:
                jubaoType = 4;
                sendReport();
                break;
            case R.id.chaoxi:
                jubaoType = 5;
                sendReport();
                break;
            case R.id.saorao:
                jubaoType = 6;
                sendReport();
                break;
            case R.id.xuni:
                jubaoType = 7;
                sendReport();
                break;
            case R.id.cancel:
                if(mDialog != null){mDialog.dismiss();}
                break;
        }
    }

    private void goOtherAcitity(Intent intent){
        if(user == null){
            Intent intent1 = new Intent();
            intent1.setClass(this,LoginActivity.class);
            startActivity(intent1);
        }else{
            startActivity(intent);
        }
    }

    private AlertDialog mDialog;
    private int jubaoType = 0;
    public void showDialog() {
        View v = LayoutInflater.from(this).inflate(R.layout.report_content, null);
        initDialogViewAndListener(v);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        mDialog = builder.setView(v).create();
        mDialog.show();//这里的对话框点击取消不起作用
    }

    private void initDialogViewAndListener(View v){
        (v.findViewById(R.id.yingxiao)).setOnClickListener(this);
        (v.findViewById(R.id.yingsui)).setOnClickListener(this);
        (v.findViewById(R.id.bushi)).setOnClickListener(this);
        (v.findViewById(R.id.mingan)).setOnClickListener(this);
        (v.findViewById(R.id.chaoxi)).setOnClickListener(this);
        (v.findViewById(R.id.saorao)).setOnClickListener(this);
        (v.findViewById(R.id.xuni)).setOnClickListener(this);
        (v.findViewById(R.id.cancel)).setOnClickListener(this);//忘记给取消设置监听
    }

    public void sendReport(){
        if(mDialog != null){mDialog.dismiss();}
        new AlertDialog.Builder(this).setTitle("提醒").setMessage("确认举报该内容?")
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Map<String,String> params = new HashMap<>();
                        params.put("targetId",id+"");
                        params.put("type","1");
                        params.put("descIndex", jubaoType + "");
                        params.put("acc_token",UserTools.getUser(BigShootDetailActivity.this).getAcc_token());
                        VolleyTool.get(BigShootDetailActivity.this, Constants.REPORT_URL, params, null, 0, null);
                        Toast.makeText(BigShootDetailActivity.this,"我们已经收到您的举报，我们会认真审查",Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                }).show();
    }

    private void goLogin(){
        Intent intent = new Intent();
        intent.setClass(this, LoginActivity.class);
        //startActivity(intent);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        user =(UserBean.User) data.getSerializableExtra("user");
    }
}
